package com.guoqi.weinstall

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.widget.Toast

open class MainActivity : AppCompatActivity() {
    private val PERMISSIONS_STORAGE =
        arrayOf("android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE")

    private var permissionListener = object : PermissionListener {
        override fun granted() {

        }

        override fun denied(deniedList: List<String>) {
            if (deniedList.isNotEmpty()) {
                showPermissionManagerDialog(this@MainActivity, deniedList as ArrayList<String>)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        requestRuntimePermissions(PERMISSIONS_STORAGE, permissionListener)
    }

    /**
     * 申请权限
     */
    fun requestRuntimePermissions(permissions: Array<String>, listener: PermissionListener) {
        if (Build.VERSION.SDK_INT < 23) {
            return
        }
        var permissionList = ArrayList<String>()
        // 遍历每一个申请的权限，把没有通过的权限放在集合中
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !== PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission)
            } else {
                permissionListener?.granted()
            }
        }
        // 申请权限
        if (permissionList.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toTypedArray(), 1)
        }
    }


    /**
     * 申请后的处理
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty() && permissionListener != null) {
            val deniedList = ArrayList<String>()
            // 遍历所有申请的权限，把被拒绝的权限放入集合
            for (i in grantResults.indices) {
                val grantResult = grantResults[i]
                if (grantResult == PackageManager.PERMISSION_GRANTED) {
                    permissionListener?.granted()
                } else {
                    //var alwaysDenied = hasAlwaysDeniedPermission(this, permissions[i])
                    deniedList.add(permissions[i])
                }
            }
            if (deniedList.isNotEmpty()) {
                permissionListener?.denied(deniedList)
            }
        }
    }

    /**
     * 显示权限弹框提示
     */
    fun showPermissionManagerDialog(context: Context, permissions: ArrayList<String>) {
        AlertDialog.Builder(context).setTitle("权限被禁用")
            .setMessage("请在 设置-应用管理-" + context.getString(R.string.app_name) + "-权限管理, 打开权限!")
            .setCancelable(false)
            .setNegativeButton("取消") { _, _ ->
                run {
                    requestRuntimePermissions(permissions.toTypedArray(), permissionListener)
                }
            }
            .setPositiveButton("去设置") { _, _ ->
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.data = Uri.fromParts("package", context.packageName, null)
                startActivityForResult(intent, 1000)
                Toast.makeText(this@MainActivity, "请授予应用相关权限", Toast.LENGTH_LONG).show()
            }.show()
    }

}

interface PermissionListener {
    fun granted()
    fun denied(deniedList: List<String>)
}
